jQuery text ()
The text() method in jQuery is used to get or set the text content of
selected elements.
Syntax
- To get text: $(selector).text();
- To set text: $("selector").text("new text");
- To set text using function: $(selector).text(function(index,currentcontent));
- Content (Mandatory):Specifies the new text to be applied to the selected elements. Any special characters in this parameter will be automatically encoded.
- Function (index, currentContent) (Optional):A callback function that defines the new text for each selected element.
- index: The position of the current element in the selection.
- currentContent: The existing text content of the current element.
Difference between jQuery text() and jQuery html()
- The jQuery text () method is used to set or return text content without HTML markup, while the html() method sets or returns the inner HTML, which includes both text and HTML markup.
- The text() method works with both XML and HTML documents, whereas the html() method is specifically for HTML documents.
To get text ():
<!DOCTYPE html>
<html>
<body>
<p id="example">Hello,
<strong>World!</strong></p>
<script>
var text = $("#example").text();
console.log(text); // Output: "Hello, World!"
</script>
</body>
</html>
To set text ():
<!DOCTYPE html>
<html>
<body>
<p id="example">Hello,
<strong>World!</strong></p>
<script>
$("#example").text("New Text Here");
// Now, the content of the paragraph becomes: "New Text Here"
</script>
</body>
</html>